<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="100px">

      <el-form-item label="制单时间">
        <el-date-picker
          v-model="daterangeDocDt"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          style="width: 250px"
        ></el-date-picker>
      </el-form-item>

      <el-form-item label="计划订单号" prop="docNum">
        <el-input
          v-model="queryParams.docNum"
          placeholder="请输入计划订单号模糊查询"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="销售号" prop="orderDocNum">
        <el-input
          v-model="queryParams.orderDocNum"
          placeholder="请输入销售号模糊查询"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="审核状态" prop="oaDictConfirmStatus">
        <el-select v-model="queryParams.oaDictConfirmStatus" clearable placeholder="请选择审核状态">
          <el-option
            v-for="dict in dict.type.oa_dict_confirm_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['erp:ps:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['erp:ps:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['erp:ps:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['erp:ps:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="erpPsList" :highlight-current-row="true" stripe @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50" align="center"  fixed="left"/>

      <el-table-column type="expand" >
        <template slot-scope="props">
          <el-form label-position="left" class="demo-table-expand">
            <el-form-item label="备注：">
              <span>{{ props.row.docNote }}</span>
            </el-form-item>
            <el-form-item label="审核人：">
              <span>{{ props.row.confirmUserName }}</span>
            </el-form-item>
            <el-form-item label="审核结果：">
              <dict-tag :options="dict.type.oa_dict_confirm_status" :value="props.row.oaDictConfirmStatus"/>
            </el-form-item>
            <el-form-item label="审核时间：">
              <span>{{ props.row.confirmDt }}</span>
            </el-form-item>
            <el-form-item label="审核意见：">
              <span>{{ props.row.confirmNote }}</span>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column label="制单时间" align="center" prop="docDt" width="150"/>
      <el-table-column label="计划订单号" align="center" prop="docNum" width="150"/>
      <el-table-column label="物料名称" align="center" prop="itemName" width="150" :show-overflow-tooltip="true"/>
      <el-table-column label="物料编码" align="center" prop="itemNum" width="160"/>
      <el-table-column label="规格" align="center" prop="itemSpecification" width="120"/>
      <el-table-column label="数量" align="center" prop="psQty"/>
      <el-table-column label="计量单位" align="center" prop="wmsDictMeasuringUnit" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.wms_dict_measuring_unit" :value="scope.row.wmsDictMeasuringUnit"/>
        </template>
      </el-table-column>
      <el-table-column label="产品名称" align="center" prop="orderItemName" width="180" :show-overflow-tooltip="true"/>
      <el-table-column label="产品编码" align="center" prop="orderItemNum" width="160"/>

      <el-table-column label="数量" align="center" prop="orderDetailQty"/>
      <el-table-column label="计量单位" align="center" prop="orderUnit" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.wms_dict_measuring_unit" :value="scope.row.orderUnit"/>
        </template>
      </el-table-column>
      <el-table-column label="制单人" align="center" prop="attentionUserName"/>

      <el-table-column label="工艺规程" align="center" prop="processDocNum" width="150"/>

      <el-table-column label="销售号" align="center" prop="orderDocNum" width="150">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="show_order(scope.row)"
          >{{scope.row.orderDocNum}}<i class="el-icon-caret-right"></i>
          </el-button>
        </template>
      </el-table-column>

      <el-table-column label="开始日期" align="center" prop="dtStart" width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.dtStart, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束日期" align="center" prop="dtEnd" width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.dtEnd, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>


      <el-table-column label="审核状态" align="center" prop="oaDictConfirmStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.oa_dict_confirm_status" :value="scope.row.oaDictConfirmStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="已完成" align="center" prop="sysYesNoDone" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.sysYesNoDone"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['erp:ps:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['erp:ps:remove']"
            :disabled="scope.row.oaDictConfirmStatus !='editing'">删除
          </el-button>

          <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)" v-hasPermi="['com:dropdown:more']">
            <span class="el-dropdown-link">
              <i class="el-icon-d-arrow-right el-icon--right"></i>更多
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="handle_newTask" icon="el-icon-share"
                                v-hasPermi="['erp:ps:launch']"
                                :disabled="scope.row.oaDictConfirmStatus != 'pass'">投放</el-dropdown-item>
              <el-dropdown-item command="showDialog_confirm" icon="el-icon-success"
                                v-hasPermi="['oa:confirm:edit']"
                                :disabled="scope.row.oaDictConfirmStatus !='waiting'">审核</el-dropdown-item>
              <el-dropdown-item command="setDone" icon="el-icon-s-flag"
                                v-hasPermi="['com:single:done']">完成</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>

        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 对话框（1）：添加或修改 - 添加或修改计划订单对话框 -->
    <el-dialog v-dialogDrag v-dialogDragWidth :title="title" :visible.sync="open" width="850px" append-to-body :close-on-click-modal=false>
      <el-form ref="form" :model="form"  label-width="100px" :rules="rules">
        <el-alert v-show="form.oaDictConfirmStatus != 'editing'"
                  style="margin-bottom: 15px;"
                  :title="form.latestTaskInfo"
                  type="info"
                  :closable="false"
                  effect="dark"
        >
        </el-alert>

        <!-- 订单 -->
        <el-card class="box-card" shadow="hover" style="margin-bottom: 20px;">
          <div slot="header" class="clearfix">
            <span><b>销售订单信息</b></span>
            <el-tooltip content="显示 / 隐藏" placement="top" style="float: right; padding: 3px 0">
              <el-switch
                v-model="fold_form_order"
                active-color="#13ce66"
                inactive-color="#ff4949"
                active-value="false"
                inactive-value="true">
              </el-switch>
            </el-tooltip>
          </div>
          <div v-show="fold_form_order== 'false'">

            <el-row>
              <el-col :span="24">
                <el-form-item label="销售明细" prop="fkOrderDetailUuid">
                  <el-input v-model="form.fkOrderDetailUuid" v-show="false"/>
                  <el-input placeholder="请选择销售订单明细" :style="{width: '100%'}" v-model="form.selectedOrderDetail"
                            class="input-with-select" readonly>
                    <el-button @click="dialog_show_selectOrderDetail" slot="append" icon="el-icon-search"></el-button>
                  </el-input>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="销售编号" size="small">
                  {{form.o_docNum}}
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="物料名称" size="small">
                  {{form.o_itemName}}
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="销售日期" size="small">
                  {{form.o_docDt}}
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="物料编码" size="small">
                  {{form.o_itemNum}}
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="客户名称" size="small">
                  {{form.o_custName}}
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="订单数量" prop="docNum" size="small">
                  {{form.o_orderDetailQty}}
                </el-form-item>
              </el-col>
            </el-row>

          </div>
        </el-card>

        <!-- 工艺规程 -->
        <el-card class="box-card" shadow="hover" style="margin-bottom: 20px;">
          <div slot="header" class="clearfix">
            <span><b>工艺规程</b></span>
            <el-tooltip content="显示 / 隐藏" placement="top" style="float: right; padding: 3px 0">
              <el-switch
                v-model="fold_form_process"
                active-color="#13ce66"
                inactive-color="#ff4949"
                active-value="false"
                inactive-value="true">
              </el-switch>
            </el-tooltip>
          </div>
          <div v-show="fold_form_process== 'false'">

            <el-row>
              <el-col :span="12">
                <el-form-item prop="versionNum" >
                  <span slot="label">
                    版本号
                   <el-tooltip content="工艺规程版本号" placement="top">
                    <i class="el-icon-question"></i>
                    </el-tooltip>
                  </span>
                  <el-select
                    filterable
                    v-model="form.versionNum"
                    placeholder="请选择版本号"
                    clearable
                    size="small"
                    :style="{width: '100%'}"
                  >
                    <el-option
                      v-for="item in versionNumList"
                      :key="item.processUuid"
                      :label="item.versionNum"
                      :value="item.processUuid"
                    />
                  </el-select>

                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item prop="fkMesProcessUuid" label="零件">
                  <el-select
                    filterable
                    v-model="form.fkMesProcessUuid"
                    placeholder="请选择零件"
                    clearable
                    size="small"
                    :style="{width: '100%'}"
                  >
                    <el-option
                      v-for="item in partList"
                      :key="item.processUuid"
                      :label="item.itemName"
                      :value="item.processUuid"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item prop="processAmt" label="规程数量">
                  {{form.processAmt}}
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item prop="processWmsDictMeasuringUnit" label="计量单位">
                  {{form.processWmsDictMeasuringUnit}}
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </el-card>
        <el-row>

          <el-col :span="12">
            <el-form-item label="计划订单号" prop="docNum">
              <el-input v-model="form.docNum" placeholder="请输入计划订单号"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="数量" prop="psQty">
              <el-input-number v-model="form.psQty" placeholder="请输入数量" :style="{width: '100%'}"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="开始日期" prop="dtStart">
              <el-date-picker clearable
                              v-model="form.dtStart"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="选择开始日期"
                              :style="{width: '100%'}">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束日期" prop="dtEnd">
              <el-date-picker clearable
                              v-model="form.dtEnd"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="选择结束日期"
                              :style="{width: '100%'}">
              </el-date-picker>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="制单时间" prop="docDt">
              <el-date-picker clearable size="small"
                              v-model="form.docDt"
                              type="datetime"
                              value-format="yyyy-MM-dd HH:mm"
                              placeholder="选择单据时间"
                              :style="{width: '100%'}" clearable>
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="制单人" prop="fkAttentionUserId">
              <el-input v-model="form.fkAttentionUserId" v-show="false"/>
              <el-input placeholder="请选择制单人" v-model="form.selectedAttentionUser" class="input-with-select">
                <el-button @click="showDialog_selectAttentionUser(form)" :style="{width: '100%'}" slot="append"
                           icon="el-icon-search"></el-button>
              </el-input>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="备注" prop="docNote">
              <el-input v-model="form.docNote" autosize type="textarea" placeholder="请输入内容" maxlength="50"
                        show-word-limit/>
            </el-form-item>
          </el-col>
        </el-row>


      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :disabled="form.oaDictConfirmStatus != 'editing'">确 定</el-button>
        <el-button type="warning" @click="submitForm('waiting')" :disabled="form.oaDictConfirmStatus != 'editing'">提交待审
        </el-button>
          <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 投放：计划订单投放生成车间生产任务 -->
    <el-dialog v-dialogDrag v-dialogDragWidth :title="title_task" :visible.sync="dialog_visible_task" width="800px" append-to-body :close-on-click-modal=false>
      <el-form ref="form_task" :model="form_task" label-width="90px" :rules="rules_task">

        <el-alert v-show="form_task.error_alert_show"
                  style="margin-bottom: 15px;"
                  title="投放失败！"
                  :description="form_task.error_alert_msg"
                  type="error"
                  :closable="true"
                  show-icon
                  effect="dark"
        >
        </el-alert>

        <el-form-item label="计划订单uuid" prop="fkErpPsUuid" v-show="false">
          <el-input v-model="form_task.fkErpPsUuid" placeholder="请输入计划订单"/>
        </el-form-item>

        <el-form-item label="工艺规程uuid" prop="fkMesProcessUuid" v-show="false">
          <el-input v-model="form_task.fkMesProcessUuid" />
        </el-form-item>

        <el-row>
          <el-col :span="12">

            <el-form-item label="任务号" prop="docNum">
              <el-input v-model="form_task.docNum" placeholder="请输入单据编号"/>
            </el-form-item>

            <el-form-item prop="taskQty">
              <span slot="label">
                数量
                <el-tooltip content="计划投放数量" placement="top">
                  <i class="el-icon-question"></i>
                </el-tooltip>
              </span>
              <el-input-number v-model="form_task.taskQty" placeholder="请输入数量" :style="{width: '100%'}"/>
            </el-form-item>

            <el-form-item label="开始日期" prop="docDtStart">
              <el-date-picker clearable
                              v-model="form_task.docDtStart"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="选择开始日期"
                              :style="{width: '100%'}">
              </el-date-picker>
            </el-form-item>

            <el-form-item label="投放时间" prop="docDt">
              <el-date-picker clearable
                              v-model="form_task.docDt"
                              type="datetime"
                              format="yyyy-MM-dd HH:mm"
                              value-format="yyyy-MM-dd HH:mm"
                              placeholder="选择结束时间"
                              :style="{width: '100%'}"
                              >
              </el-date-picker>
            </el-form-item>
          </el-col>

          <el-col :span="12">

            <el-form-item label="车间" prop="fkDeptId">
              <el-select
                filterable
                v-model="form_task.fkDeptId"
                placeholder="请选择车间"
                clearable
                size="small"
                :style="{width: '100%'}">
                <el-option
                  v-for="item in deptList"
                  :key="item.fkDeptId"
                  :label="item.deptName"
                  :value="item.fkDeptId"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="经办人" prop="fkAttentionUserId">
              <el-input v-model="form_task.fkAttentionUserId" v-show="false"/>
              <el-input placeholder="请选择经办人" v-model="form_task.selectedAttentionUser" class="input-with-select">
                <el-button @click="showDialog_selectTaskAttentionUserName(form_task)" :style="{width: '100%'}" slot="append"
                           icon="el-icon-search"></el-button>
              </el-input>
            </el-form-item>

            <el-form-item label="结束日期" prop="docDtEnd">
              <el-date-picker clearable
                              v-model="form_task.docDtEnd"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="选择结束日期"
                              :style="{width: '100%'}"
                              >
              </el-date-picker>
            </el-form-item>

          </el-col>

          <el-col :span="24">
            <el-form-item label="备注" prop="docNote">
              <el-input v-model="form_task.docNote" placeholder="请输入备注" :style="{width: '100%'}" type="textarea"
                        autosize maxlength="500" show-word-limit rows="2" />
            </el-form-item>
          </el-col>

        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm_task">确 定</el-button>
          <el-button @click="cancel_task()">取 消</el-button>
      </div>
    </el-dialog>


    <select-orderDetail ref="component_selectOrderDetail" @ok="selectOrder_done"/>
    <select-user ref="component_selectAttentionUser" @ok="selectAttentionUser_done" />
    <select-user ref="component_selectTaskAttentionUserName" @ok="selectTaskAttentionUserName_done" />
    <confirm ref="component_confirm" @ok="confirm_done"/>
  </div>
</template>

<script>
  import {listPs, getPs, delPs, addPs, updatePs} from "@/api/erp/ps";
  import selectOrderDetail from "../../crm/crmOrders/selectOrderDetail";
  import { listProcess } from "@/api/mes/process";
  import {newDocNum} from "@/api/oa/docNum";
  import selectUser from "../../comn/userGroup/selectUser";
  import {addTasks} from "@/api/mes/tasks";
  import {listDeptGroup} from "@/api/comn/deptGroup";
  import confirm from "../../oa/confirm";
  import { parseTime } from '@/utils/ruoyi'
  import { getInfo } from '@/api/login'
  export default {
    name: "Ps",
    dicts: ['sys_normal_disable', 'oa_dict_confirm_status','sys_yes_no','wms_dict_measuring_unit'],
    components: {selectOrderDetail, selectUser, confirm},
    data() {
      let validateStartTime = (rule, value, callback) => {
        if (!value) {
          callback(new Error("开始日期不能为空"));
        } else {
          // 如果结束日期没选
          if (!this.form_task.docDtEnd) {
            callback();
          } else {
            // 结束日期有进行判断
            if (this.compareDate(value, this.form_task.docDtEnd)) {
              // 如果起始在结束之前
              callback();
            } else {
              callback(new Error("开始日期不能再结束日期之后，请重新选择"));
            }
          }
        }
      };
      let validateEndTime = (rule, value, callback) => {
        if (!value) {
          callback(new Error("结束日期不能为空"));
        } else {
          if (!this.form_task.docDtStart) {
            callback();
          } else {
            // 起始日期有
            if (this.compareDate(this.form_task.docDtStart, value)) {
              callback();
            } else {
              callback(new Error("结束日期不能在开始日期前，请重新选择"));
            }
          }
        }
      };


      let validateDtStart = (rule, value, callback) => {
        if (!value) {
          callback(new Error("开始日期不能为空"));
        } else {
          // 如果结束日期没选
          if (!this.form.dtEnd) {
            callback();
          } else {
            // 结束日期有进行判断
            if (this.compareDate(value, this.form.dtEnd)) {
              // 如果开始日期在结束日期之前
              callback();
            } else {
              callback(new Error("开始日期不能再结束日期之后，请重新选择"));
            }
          }
        }
      };
      let validateDtEnd = (rule, value, callback) => {
        if (!value) {
          callback(new Error("结束日期不能为空"));
        } else {
          if (!this.form.dtStart) {
            callback();
          } else {
            // 开始日期有
            if (this.compareDate(this.form.dtStart, value)) {
              callback();
            } else {
              callback(new Error("结束日期不能在开始日期前，请重新选择"));
            }
          }
        }
      };

      return {
        // 遮罩层
        loading: true,
        fold_form_order: 'false',
        fold_form_process: 'false',
        currUser:{
          userId: null,
          nickName: null
        },
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        daterangeDocDt: [],
        partList: [],
        processList: [],
        deptList: [],
        versionNumList: [],
        // 计划订单表格数据
        erpPsList: [],
        // 弹出层标题
        title: "",
        title_task: "",
        // 是否显示弹出层
        open: false,
        dialog_visible_task: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          fkOrderDetailUuid: null,
          fkMesProcessUuid: null,
          psQty: null,
          dtStart: null,
          dtEnd: null,
          sysNormalDisable: null,
          docTitle: null,
          docNum: null,
          docDt: null,
          docNote: null,
          fkItemUuid: null,
          fkAttentionUserId: null,
          fkConfirmUserId: null,
          confirmDt: null,
          oaDictConfirmStatus: null,
          confirmNote: null,
        },
        // 表单参数
        form: {
          processAmt: null ,
          fkAttentionUserId: null ,
        },
        form_task: {
        },
        // 表单校验
        rules: {
          fkOrderDetailUuid: [
            {required: true, message: "订单明细不能为空", trigger: "change"}
          ],
          versionNum: [
            {required: true, message: "版本号不能为空", trigger: "change"}
          ],
          fkMesProcessUuid: [
            {required: true, message: "零件不能为空", trigger: "change"}
          ],
          docNum: [
            {required: true, message: "计划订单号不能为空", trigger: "change"}
          ],
          psQty: [
            {required: true, message: "数量不能为空", trigger: "change"}
          ],
          fkAttentionUserId: [
            {required: true, message: "经办人不能为空", trigger: "change"}
          ],
          dtStart: [
            {
              required: true,
              trigger: ["change"],
              validator: validateDtStart,
            },
          ],
          dtEnd: [
            {
              required: true,
              trigger: ["change"],
              validator: validateDtEnd,
            },
          ],
          docDt: [
            {required: true, message: "制单时间不能为空", trigger: "change"}
          ],
        }   ,
        rules_task: {
          docNum: [
            {required: true, message: "任务号不能为空", trigger: "change"}
          ],
          fkDeptId: [
            {required: true, message: "车间不能为空", trigger: "change"}
          ],
          taskQty: [
            {required: true, message: "数量不能为空", trigger: "change"}
          ],
          fkAttentionUserId: [
            {required: true, message: "经办人不能为空", trigger: "change"}
          ],
          docDtStart: [
            {
              trigger: ["change"],
              validator: validateStartTime,
            },
          ],
          docDtEnd: [
            {
              trigger: ["change"],
              validator: validateEndTime,
            },
          ],
          docDt: [
            {required: true, message: "投放时间不能为空", trigger: "change"}
          ],
        },

      };
    },

    created() {
      // $route params
      let erpPsDocNum = this.$route.params && this.$route.params.erpPsDocNum;
      if (erpPsDocNum) {
        this.queryParams.docNum = erpPsDocNum
      }else console.log('！！！ 无参数 ！！！')
      // var userId = this.$store.state.user.userId;
      console.log(this.$store.state.user.nickName)
      getInfo().then(response => {
        this.currUser = response.user
        console.log(this.currUser)
      });
      this.getList();
      this.getList_dept()
    },
    methods: {
      // 比较两个日期
      compareDate(start, end) {
        return new Date(end).getTime() >= new Date(start).getTime();
      },


      /** 打开对话框：审核 */
      showDialog_confirm(row) {
        console.log(row)
        let obj = {
          tableName: 'erp_ps',
          uuidColumn: 'erp_ps_uuid',
          fkUuid: row.erpPsUuid,
          attentionUserNickName: row.attentionUserName,
          oaDictConfirmStatus: row.oaDictConfirmStatus,
          msg: `请审核计划订单, 单据编号：${row.docNum}`
        }
        this.$refs.component_confirm.showDialog_confirm(obj);
      },

      confirm_done() {
        this.getList()
      },

      /** 查询计划订单列表 */
      getList() {
        this.loading = true;
        this.queryParams.params = {};
        if (null != this.daterangeDocDt && '' != this.daterangeDocDt) {
          this.queryParams.params["beginDocDt"] = this.daterangeDocDt[0];
          this.queryParams.params["endDocDt"] = this.daterangeDocDt[1];
        }
        listPs(this.queryParams).then(response => {
          this.erpPsList = response.rows;
          console.log(this.erpPsList)
          this.total = response.total;
          this.loading = false;
        });
      },

      /** 列表: 部门（车间） */
      getList_dept() {
        listDeptGroup({comnDictDeptGroup: 'workshop'}).then(response => {
          this.deptList = response.rows;
        });
      },

      /** 获取工艺规程的版本号 */
      getList_versionNum() {
        let param = {fkItemUuid: this.form.fkItemUuid, parentUuid: 0,}
        console.log(param)
        listProcess(param).then(response => {
          this.versionNumList = response.rows;
          console.log(this.versionNumList)
        });
      },

      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },

      // 取消按钮
      cancel_task() {
        this.dialog_visible_task = false;
        this.reset_task();
      },
      // 表单重置
      reset() {
        this.form = {
          erpPsUuid: null,
          fkOrderDetailUuid: null,
          fkMesProcessUuid: null,
          itemName: null,
          versionNum: null,
          dtStart: null,
          dtEnd: null,
          sysNormalDisable: null,
          processWmsDictMeasuringUnit: null,
          processAmt: null,
          docTitle: null,
          docNum: null,
          docDt: parseTime(Date.now(), '{y}-{m}-{d} {h}:{i}'),
          docNote: null,
          fkAttentionUserId: this.currUser.userId,
          fkConfirmUserId: null,
          confirmDt: null,
          oaDictConfirmStatus: null,
          confirmNote: null,
          createBy: null,
          createTime: null,
          updateBy: null,
          updateTime: null,
          orderDocNum: null,
          orderDocDt:  null
        };
        this.resetForm("form");
      },

      reset_task() {
        this.form_task = {
          docNum: null,
          taskQty: 1,
          dtStart: null,
          fkDeptId: null,
          docDtStart: null,
          docDtEnd: null,
          fkAttentionUserId: this.currUser.userId,
          fkErpPsUuid: null,
          fkMesProcessUuid: null,
          selectedAttentionUser: null,
          docDt: parseTime(Date.now(), '{y}-{m}-{d} {h}:{i}'),
          error_alert_show: false,
          error_alert_msg: '',
        };
        this.resetForm("form_task");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.erpPsUuid)
        this.docDts = selection.map(item => item.docDt)
        this.docNums = selection.map(item => item.docNum)
        this.single = selection.length !== 1
        this.oaDictConfirmStatus = selection.map(i=>i.oaDictConfirmStatus)
        this.multiple=
          (this.oaDictConfirmStatus.indexOf('editing')>-1 && [...new Set(this.oaDictConfirmStatus)]=='editing') ? false : true
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();

        newDocNum({preCode: 'ERP-', len: 12}).then(response => {
          this.form.docNum = response.msg
        })

        this.form.selectedAttentionUser = `${this.currUser.nickName}（${this.currUser.userId}）`
        this.form.oaDictConfirmStatus = 'editing'
        this.open = true;
        this.title = "添加计划订单";
      },

      /** 投放按钮操作 */
      handle_newTask(row) {
        this.reset_task()


        // getLatestTaskByErpPsUuid(row.erpPsUuid).then(response => {
        //   let d = response.data
        //   let m = '💡 最近一次由该计划订单投放的车间任务'
        //   if( d ){
        //     m = `${m}时间为：${d.docDt}，经办人：${ d.attentionUserName }`
        //   }else {
        //     m = `${m}：(未查询到相关数据)`
        //   }
        //   this.form_task.latestTaskInfo = m
        // });

        console.log(row)
        this.form_task.fkErpPsUuid = row.erpPsUuid
        this.form_task.fkMesProcessUuid = row.fkMesProcessUuid
        this.form_task.taskQty = row.psQty

        newDocNum({preCode: 'TSK-', len: 12}).then(response => {
          this.form_task.docNum = response.msg
          console.log(this.form_task.docNum)
        })

        this.form_task.selectedAttentionUser = `${this.currUser.nickName}（${this.currUser.userId}）`
        this.dialog_visible_task = true;
        this.title_task = "计划订单投放";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const erpPsUuid = row.erpPsUuid || this.ids
        getPs(erpPsUuid).then(response => {
          this.form = response.data;
          console.log(this.form)
          this.form.selectedOrderDetail =
            `物料名称：${this.form.orderItemName}，物料编码：${this.form.itemNum}，订单编号：${this.form.orderDocNum}`;
          this.form.o_docNum = this.form.orderDocNum;
          this.form.o_itemName = this.form.orderItemName;
          this.form.o_docDt = this.form.orderDocDt;
          this.form.o_itemNum = this.form.itemNum;
          this.form.o_custName = this.form.custName;
          this.form.o_orderDetailQty = this.form.orderDetailQty;
          this.form.selectedAttentionUser =
            `${this.form.attentionUserName}（${this.form.fkAttentionUserId}）`
          this.form.processAmt = this.form.processAmt
          this.form.processWmsDictMeasuringUnit = this.selectDictLabel(this.dict.type.wms_dict_measuring_unit,this.form.wmsDictMeasuringUnit)

          let param = {fkItemUuid: this.form.fkItemUuid, parentUuid: 0,}
          console.log(param)
          listProcess({fkItemUuid: this.form.fkItemUuid, parentUuid: 0}).then(response => {
            this.versionNumList = response.rows;
            console.log(this.versionNumList )
          });

          listProcess({fkItemUuid:this.form.fkItemUuid}).then(response => {
            this.partList = response.rows;
            console.log(this.partList)
          });
          this.form.oaDictConfirmStatus =
            ('editing' == this.form.oaDictConfirmStatus || 'reject' == this.form.oaDictConfirmStatus)
              ? 'editing' : this.form.oaDictConfirmStatus


          if(row.oaDictConfirmStatus!='editing'||row.oaDictConfirmStatus!='reject'||this.oaDictConfirmStatus!='editing'||this.oaDictConfirmStatus!='reject'){
            this.form.latestTaskInfo='💡 该条记录审核状态为'+
              this.selectDictLabel(this.dict.type.oa_dict_confirm_status, row.oaDictConfirmStatus||this.oaDictConfirmStatus)+'状态'+','+'不能修改'
          }

          this.open = true;
          this.title = "修改计划订单";
        });
      },
      /** 提交按钮 */
      submitForm(confirmStatus) {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if(confirmStatus=='waiting') this.form.oaDictConfirmStatus = confirmStatus
            if (this.form.erpPsUuid != null) {
              updatePs(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addPs(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },

      /** 提交按钮 */
      submitForm_task() {
        this.$refs["form_task"].validate(valid => {
          if (valid) {
            console.log(this.form_task)
            addTasks(this.form_task).then(response => {
              this.$modal.msgSuccess("投放成功");
              this.dialog_visible_task = false;
            }).catch(err=>{
              // console.log(err)
              this.form_task.error_alert_show = true
              this.form_task.error_alert_msg = err
            });
          }
        })
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const erpPsUuids = row.erpPsUuid || this.ids;
        const docDts = row.docDt || this.docDts;
        const docNums = row.docNum || this.docNums;
        this.$modal.confirm('是否确认删除制单时间为"' + docDts + '",计划订单号为"' + docNums + '"的计划订单？','删除确认').then(function () {
          return delPs(erpPsUuids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {
        });
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('erp/erp/ps/export', {
          ...this.queryParams
        }, `post_${new Date().getTime()}.xlsx`)
      },

      /** 选择经办人 */
      showDialog_selectAttentionUser( form ) {
        this.currentForm = form
        // this.$refs.component_selectAttentionUser.userGroup = 'worker';
        this.$refs.component_selectAttentionUser.show();
      },

      /** 选择经办人 - 完成 */
      selectAttentionUser_done(user) {
        this.currentForm.fkAttentionUserId = user.userId
        this.currentForm.selectedAttentionUser = user.userNickNameAndId
      },

      /** 选择车间任务经办人 */
     showDialog_selectTaskAttentionUserName( form_task ) {
        this.currentForm = form_task
        // this.$refs.component_selectTaskAttentionUserName.userGroup = 'worker';
        this.$refs.component_selectTaskAttentionUserName.show();
      },

      /** 选择车间任务经办人 - 完成 */
      selectTaskAttentionUserName_done(user) {
        this.currentForm.fkAttentionUserId = user.userId
        this.currentForm.selectedAttentionUser = user.userNickNameAndId
      },

      /** 显示对话框：选择订单 */
      dialog_show_selectOrderDetail() {
        this.$refs.component_selectOrderDetail.dialog_show_selectOrderDetail();
      },

      /** 选择订单明细完成 */
      selectOrder_done(user) {
        console.log(user)
        this.form.fkOrderDetailUuid = user.row.orderDetailUuid;
        this.form.selectedOrderDetail =
          `物料名称：${user.row.itemName}，物料编码：${user.row.itemNum}，订单编号：${user.row.docNum}`;
        this.form.o_docNum = user.row.docNum;
        this.form.o_itemName = user.row.itemName;
        this.form.o_docDt = user.row.docDt;
        this.form.o_itemNum = user.row.itemNum;
        this.form.o_custName = user.row.custName;
        this.form.o_orderDetailQty = `${user.row.orderDetailQty}（${this.selectDictLabel(this.dict.type.wms_dict_measuring_unit,
          user.row.wmsDictMeasuringUnit)}）`;
        this.form.order_orderDetailQty = user.row.orderDetailQty
        this.form.fkItemUuid = user.row.orderDetailItemUuid;
        this.getList_versionNum()
      },

      // 更多操作触发
      handleCommand(command, row) {
        switch (command) {
          case "handle_newTask":
            this.handle_newTask(row);
            break;
          case "showDialog_confirm":
            this.showDialog_confirm(row);
            break;
          case "setDone":
            let id = row.erpPsUuid

            this.$modal.confirm( `是否确认计划订单号为 ${row.docNum} 的计划订单已完成？`, '完成确认').then(function() {
              let d = {
                erpPsUuid: id,
                sysYesNoDone: row.sysYesNoDone == 'Y' ? 'N':'Y'
              }
              return updatePs(d).then(response => {
              });
            }).then(() => {
              this.$modal.msgSuccess("修改成功");
              this.getList();
            }).catch(() => {});
            break;
          default:
            break;
        }
      },

      // 显示 - 销售号
      show_order(r) {
        console.log(r)
        this.$router.push(`/crm/crmOrders/docNum/${r.orderDocNum}`);
      },

    },
    watch:{
      'form.versionNum'(newValue, oldValue) {
        console.log(newValue)
        if(newValue != null && newValue != ""){
          listProcess({processUuid:newValue}).then(response => {
            this.partList = response.rows;
            console.log(this.partList)
          });
        }
        },

      'form.fkMesProcessUuid'(oldValue,newValue) {
        console.log(oldValue)
        if(oldValue != null && oldValue != "") {
          listProcess({fkMesProcessUuid: oldValue}).then(response => {
            this.processList = response.rows;
            console.log( this.processList )
            this.form.processAmt = this.processList[0].processAmt
            this.form.processWmsDictMeasuringUnit = this.selectDictLabel(this.dict.type.wms_dict_measuring_unit, this.processList[0].wmsDictMeasuringUnit)
            console.log(this.form.order_orderDetailQty)
            console.log(this.form.processAmt)
            this.form.psQty = (this.form.order_orderDetailQty)*(this.form.processAmt)
            console.log(this.form.psQty)
          });
        }
        },
    },
  };
</script>
